const dayjs = require("dayjs");
const { By } = require("selenium-webdriver");
const selenium = require("selenium-webdriver");

const driver = new selenium.Builder().forBrowser("chrome").build();

// 最大化浏览器
// driver.manage().window().maximize();

driver.get("https://www.vmall.com/product/10086970184614.html");
// driver.get("https://www.vmall.com/product/10086750782673.html#2601010424808");
// driver.get("http://localhost:4000/");

// 类似于python中time的sleep函数
const sleep = (time) => {
  return new Promise((resolve) => {
    setTimeout(resolve, time * 1000);
  });
};

// 登录
const login = async () => {
  console.log("尝试登录");
  const loginText = driver.findElement(By.linkText("请登录"));
  if (loginText) loginText.click();
  // //   console.log("请在30秒内完成扫码");
  await sleep(30);
  console.log("开始抢购");
  // 当天的 18:08:00
  buy(
    dayjs()
      .set("hour", 18)
      .set("minute", 8)
      .set("second", 0)
      .format("YYYY-MM-DD HH:mm:ss")
  );
};

// 秒杀
const buy = async (buyTime) => {
  while (true) {
    const now = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
    if (now === buyTime) {
      try {
        await queryAndClickDom("立即下单");
        // await sleep(0.1);
        console.log(
          "立即下单 dom元素轮询完毕" +
            dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
        );
        await queryAndClickDom2();
        console.log(
          "提交订单" + dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
        );
        break;
      } catch (e) {
        console.warn(e);
      }
    }
  }
};

/**
 * 轮询函数
 * 一直轮询页面 直到找到元素后停止 或者达到轮询的最大次数
 */
let count = 10000;
const queryAndClickDom = (spanName) => {
  let queryDomIntervalId = null;
  let hasFind = false;
  let intervalCount = 1;

  return new Promise((res) => {
    queryDomIntervalId = setInterval(async () => {
      try {
        // 3
        if (hasFind) return;
        let buyEls = await driver.findElements(
          By.className("product-button02")
        );

        console.log(intervalCount++);

        let currentLoop = 1;
        for (let ele of buyEls) {
          let text = await ele.getText();
          if (text === "立即下单") {
            try {
              console.log(
                `
                intervalCount: ${intervalCount}
                currentLoop: ${currentLoop} 
                hasFind: ${hasFind}
                `
              );
              if (!hasFind) {
                hasFind = true;
                console.log(
                  "点击下单" + dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
                );
                ele.click();
                clearInterval(queryDomIntervalId);
                break;
              }

              break;
            } catch (e) {
              console.warn(e);
            }
          }
        }
      } catch (e) {
        count--;
        console.warn("queryAndClickDom", e);

        // 10000次没抢到后自动停止
        if (!count) {
          console.log(queryDomIntervalId, "count 为0后 id的值");
          clearInterval(queryDomIntervalId);
          console.log("已超过1k次，停止轮询");
          return res(false);
        }
      }
    }, 50);

    console.log("setInterval id: " + queryDomIntervalId);
  });
};

const queryAndClickDom2 = (dom) => {
  let queryDomIntervalId = null;
  return new Promise((res) => {
    queryDomIntervalId = setInterval(async () => {
      try {
        // 3
        let buyEls = await driver.findElements(
          By.className("order-submit-btn")
        );

        for (let ele of buyEls) {
          let text = await ele.getText();
          console.log(text, "text");
          if (text === "提交订单") {
            ele.click();
            clearInterval(queryDomIntervalId);
            break;
          }
        }
      } catch (e) {
        count--;
        console.warn("没有找到dom元素" + e + " , count: " + count);

        // 10000次没抢到后自动停止
        if (!count) {
          console.log(queryDomIntervalId, "count 为0后 id的值");
          clearInterval(queryDomIntervalId);
          console.log("已超过1k次，停止轮询");
          return res(false);
        }
      }
    }, 50);

    console.log("setInterval id: " + queryDomIntervalId);
  });
};

login();

// const sleep = (index) =>
//   new Promise((res) => {
//     setTimeout(() => {
//       res(index);
//     }, 1000);
//   });

// (async function () {
//   for (let i of [1, 2, 3]) {
//     let res = await sleep(i);
//     console.log(res);
//     if (res === 2) {
//       break;
//     }
//   }
// })();
